﻿using Max.PH4.Shoppgin.Admin.Common;
using Max.PH4.Shoppgin.Admin.DataAccess;
using Max.PH4.Shoppgin.Admin.Domain;
using Max.PH4.Shoppgin.Admin.Domain.Shared;
using Max.PH4.Shoppgin.Admin.DTO;
using Max.PH4.Shoppgin.Admin.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Max.PH4.Shoppgin.Admin.API.Controllers
{
    [Route("order")]
    [ApiController]
    public class OrderController : ControllerBase
    {

        IOrderMasterService _orderService;

        MyDbContext _context;
        public OrderController(IOrderMasterService orderService, MyDbContext context)
        {
            _orderService = orderService;
            _context = context;
        }

        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Insert(OrderInputDto dto)
        {
            ResponseResultDto result = new();

            try
            {

                int res = _orderService.Insert(dto);
                result.Data = res;
            }
            catch (Exception ex)
            {
                result.Code = ResponseStateCode.Failed;
                result.Message = $"出错啦,{ex.Message}";
            }

            return Ok(result);
        }

        /// <summary>
        /// 订单查询
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Query(string state = "-1")
        {
            ResponseResultDto result = new();


            var data = _orderService.Query();
            result.Data = data;
            //state = state ?? "-1";

            //var data = _orderService.Query("",state, 1, 10, out int total);

            //result.Data = new { list = data, total };

            return Ok(result);
        }


        /// <summary>
        /// 获取订单明细
        /// </summary>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public IActionResult QueryDetail(string orderNo)
        {
            ResponseResultDto result = new();

            var data = _orderService.GetOrderDetail(orderNo);

            result.Data = data;

            return Ok(result);
        }




        [HttpGet("enum/bind")]
        public IActionResult QueryPayTypeEnum(string? a = "")
        {
            //var data = _orderService.GetPayEnumBind();


            if (a.Equals("pay"))
            {
                var data = ReflectionHelper.GetEnumBind(typeof(PayTypeEnum));
                return Ok(data);
            }
            else
            {
                var data = ReflectionHelper.GetEnumBind(typeof(OrderStateEnum));
                return Ok(data);
            }

        }


        #region 不用7层添加订单

        private void CreateOrder()
        {
            var order = new OrderMasterEntity();//一个订单主表
            var details = new List<OrderDetailEntity>();//多个订单商品（订单明细表）

            using (var tran = _context.Database.BeginTransaction())
            {
                try
                {
                    _context.OrderMasters.Add(order); //添加一个订单
                    _context.OrderDetails.AddRange(details); //添加这个订单对应的多个商品


                    //把添加到订单商品表（订单明细表）的商品的库存找出来，并修改
                    details.ForEach(x =>
                    {

                        bool flag = false;
                        do
                        {
                            var m = _context.SKUs.Where(s => s.Id == x.SKUId).FirstOrDefault();
                            if (m != null)
                            {
                                m.ValidStock -= Convert.ToInt32(x.SKUNumber);
                                m.LockStock += Convert.ToInt32(x.SKUNumber);

                                try
                                {
                                    _context.SKUs.Update(m);
                                    _context.SaveChanges();
                                    flag = true;
                                }
                                catch (Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException)
                                {
                                    flag = false;
                                }
                            }
                            else
                            {
                                flag = true;
                            }
                        } while (flag);

                    });


                    _context.SaveChanges();

                    tran.Commit();

                }
                catch (Exception)
                {
                    tran.Rollback();
                    throw;
                }
            }
        }

        #endregion
    }
}
